package com.es.servlet; /**
 * 描述:
 * es-servlet-
 *
 * @author Derek
 * 创建时间：2022-04-22 10:26
 */

import com.es.util.DBUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //设置编码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //
        String sql = "select username,password from sys_user where username=? and password=?";
        //
        Connection connection = DBUtils.getConnection();
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            //
            ResultSet resultSet = ps.executeQuery();
            if(resultSet.next()){
                //登录成功，把当前的用户名放入到 session
                HttpSession session = request.getSession();
                session.setAttribute("currentUser", username);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //响应部分
        response.setContentType("text/html;charset=utf-8");
        //
        PrintWriter out = response.getWriter();
        out.println("<h3>欢迎回来："+username+"</h3>");
        out.println("<a href='index.jsp'>返回首页</a>");
        out.flush();



    }
}
